package com.himiotech.core.project.web.system.monitor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.himiotech.core.framework.config.shiro.service.PasswordService;
import com.himiotech.core.framework.helper.anno.Log;
import com.himiotech.core.framework.helper.enums.BusinessType;
import com.himiotech.core.framework.helper.utils.ExcelUtil;
import com.himiotech.core.project.model.entity.LoginInfo;
import com.himiotech.core.project.model.metadata.LoginInfoMetadata;
import com.himiotech.core.project.service.ILoginInfoService;
import com.himiotech.core.project.web.base.HimioBaseController;
import com.himiotech.core.project.web.base.model.HimioResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统访问记录
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Controller
@RequestMapping("/monitor/loginInfo")
public class LoginInfoController extends HimioBaseController {

    @Autowired
    private ILoginInfoService loginInfoService;

    @Autowired
    private PasswordService passwordService;

    @RequiresPermissions("monitor:loginInfo:view")
    @GetMapping
    public String loginInfo() {
        return "monitor/loginInfo";
    }

    /**
     * 查询系统访问记录列表
     *
     * @param page      分页信息
     * @param loginInfo 查询条件
     * @return 表格分页数据
     */
    @RequiresPermissions("monitor:loginInfo:list")
    @PostMapping("/list")
    @ResponseBody
    public HimioResult list(Page<LoginInfo> page, LoginInfo loginInfo) {
        handleOrderBy(request, page);
        page = loginInfoService.selectLoginInfoListPage(page, loginInfo);
        return writeJsonLayuiTable(page);
    }

    /**
     * 导出系统访问记录列表数据
     *
     * @param loginInfo 查询条件
     * @return 导出数据
     */
    @Log(title = "系统访问记录 - 导出", businessType = BusinessType.EXPORT)
    @RequiresPermissions("monitor:loginInfo:export")
    @PostMapping("/export")
    @ResponseBody
    public HimioResult export(LoginInfo loginInfo) {
        QueryWrapper<LoginInfo> query = Wrappers.query();
        if (loginInfo != null) {
            Map<String, Object> searchParams = loginInfo.getSearchParams();
            if (!searchParams.isEmpty()) {
                String loginTimeStart = MapUtil.getStr(searchParams, StrUtil.toCamelCase(LoginInfoMetadata.LOGIN_TIME.getColName()).concat("Start")).concat(" 00:00:00");
                String loginTimeEnd = MapUtil.getStr(searchParams, StrUtil.toCamelCase(LoginInfoMetadata.LOGIN_TIME.getColName()).concat("End")).concat(" 23:59:59");
                query.ge(StrUtil.isNotEmpty(loginTimeStart), LoginInfoMetadata.LOGIN_TIME.getColName(), loginTimeStart);
                query.le(StrUtil.isNotEmpty(loginTimeEnd), LoginInfoMetadata.LOGIN_TIME.getColName(), loginTimeEnd);
            }
            query.like(ObjectUtil.isNotEmpty(loginInfo.getLoginName()), LoginInfoMetadata.LOGIN_NAME.getColName(), loginInfo.getLoginName());
            query.eq(ObjectUtil.isNotEmpty(loginInfo.getLoginLocation()), LoginInfoMetadata.LOGIN_LOCATION.getColName(), loginInfo.getLoginLocation());
            query.eq(ObjectUtil.isNotEmpty(loginInfo.getStatus()), LoginInfoMetadata.STATUS.getColName(), loginInfo.getStatus());
        }
        List<LoginInfo> list = loginInfoService.list(query);
        ExcelUtil<LoginInfo> util = new ExcelUtil<>(LoginInfo.class);
        return util.exportExcel(list, "系统访问记录");
    }

    /**
     * 删除系统访问记录
     *
     * @param ids 删除id（以逗号分隔）
     * @return 处理结果
     */
    @RequiresPermissions("monitor:loginInfo:remove")
    @Log(title = "系统访问记录 - 删除", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public HimioResult remove(String ids) {
        if (ids != null) {
            List<String> idList = Arrays.stream(ids.split(",")).collect(Collectors.toList());
            return writeJson(loginInfoService.removeByIds(idList));
        } else {
            return writeJsonOk("没有需要删除的数据");
        }
    }


    @RequiresPermissions("monitor:loginInfo:remove")
    @Log(title = "登录日志", businessType = BusinessType.CLEAN)
    @PostMapping("/clean")
    @ResponseBody
    public HimioResult clean() {
        loginInfoService.cleanLoginInfo();
        return writeJsonOk();
    }

    @RequiresPermissions("monitor:loginInfo:unlock")
    @Log(title = "账户解锁", businessType = BusinessType.OTHER)
    @PostMapping("/unlock")
    @ResponseBody
    public HimioResult unlock(String loginName) {
        passwordService.clearLoginRecordCache(loginName);
        return writeJsonOk();
    }
}
